<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>仓库管理</template>
      <template #extra>
        <a-button type="primary" @click="handleAdd">
          <template #icon><icon-plus /></template>
          新增仓库
        </a-button>
      </template>
      
      <!-- 搜索区域 -->
      <a-form :model="searchForm" class="search-form" layout="inline">
        <a-form-item field="keyword" label="关键字">
          <a-input v-model="searchForm.keyword" placeholder="仓库名称/编码" allow-clear @press-enter="handleSearch" />
        </a-form-item>
        <a-form-item field="type" label="仓库类型">
          <a-select v-model="searchForm.type" placeholder="全部类型" allow-clear>
            <a-option value="常温">常温</a-option>
            <a-option value="冷藏">冷藏</a-option>
            <a-option value="冷冻">冷冻</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select v-model="searchForm.status" placeholder="全部状态" allow-clear>
            <a-option :value="1">启用</a-option>
            <a-option :value="0">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格区域 -->
      <a-table 
        :data="warehouseList" 
        :loading="warehouseLoading" 
        :pagination="false"
        row-key="id"
        :bordered="false"
        stripe
      >
        <template #columns>
          <a-table-column title="仓库名称" data-index="name" :width="150" />
          <a-table-column title="仓库编码" data-index="code" :width="120" />
          <a-table-column title="仓库类型" data-index="type" :width="100" />
          <a-table-column title="面积(㎡)" data-index="area" :width="100" />
          <a-table-column title="容量" data-index="capacity" :width="100" />
          <a-table-column title="温度(°C)" :width="120">
            <template #cell="{ record }">
              <span v-if="record.min_temperature !== null || record.max_temperature !== null">
                {{ record.min_temperature ?? 'N/A' }} ~ {{ record.max_temperature ?? 'N/A' }}
              </span>
              <span v-else>--</span>
            </template>
          </a-table-column>
          <a-table-column title="湿度(%)" :width="120">
            <template #cell="{ record }">
              <span v-if="record.min_humidity !== null || record.max_humidity !== null">
                {{ record.min_humidity ?? 'N/A' }} ~ {{ record.max_humidity ?? 'N/A' }}
              </span>
              <span v-else>--</span>
            </template>
          </a-table-column>
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="220">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-divider direction="vertical" />
                <a-button type="text" size="small" @click="toggleStatus(record)">
                  {{ record.status === 1 ? '禁用' : '启用' }}
                </a-button>
                <a-divider direction="vertical" />
                <a-popconfirm
                  content="删除仓库会影响其下库位及库存，确定删除吗？"
                  @ok="handleDelete(record.id)"
                >
                  <a-button type="text" status="danger" size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="warehousePagination.current"
          v-model:pageSize="warehousePagination.pageSize"
          :total="warehousePagination.total"
          show-total
          show-jumper
          show-page-size
          :page-size-options="[10, 20, 50, 100]"
          @change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
    </a-card>

    <!-- 新增/编辑模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleOk"
      @cancel="handleCancel"
      :mask-closable="false"
      :on-before-ok="validateForm"
      :ok-loading="submitLoading"
      unmount-on-close
      width="600px"
    >
      <a-form ref="formRef" :model="formModel" :rules="formRules" layout="vertical">
        <a-form-item field="name" label="仓库名称" required>
          <a-input v-model="formModel.name" placeholder="请输入仓库名称" allow-clear />
        </a-form-item>
        <a-form-item field="code" label="仓库编码" required>
          <a-input v-model="formModel.code" placeholder="请输入仓库编码 (如 CW001)" allow-clear :disabled="isEdit"/>
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="type" label="仓库类型" required>
              <a-select v-model="formModel.type" placeholder="请选择仓库类型">
                <a-option value="常温">常温</a-option>
                <a-option value="冷藏">冷藏</a-option>
                <a-option value="冷冻">冷冻</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="status" label="状态" required>
              <a-radio-group v-model="formModel.status" type="button">
                <a-radio :value="1">启用</a-radio>
                <a-radio :value="0">禁用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="面积(㎡)" field="area">
              <a-input-number v-model="formModel.area" :precision="2" :step="10" :min="0" placeholder="请输入仓库面积" style="width: 100%;" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="容量" field="capacity">
              <a-input-number v-model="formModel.capacity" :precision="0" :step="100" :min="0" placeholder="请输入仓库容量(如托盘数)" style="width: 100%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="最低温度(°C)" field="min_temperature">
              <a-input-number 
                v-model="formModel.min_temperature" 
                :precision="1" 
                :step="0.5" 
                placeholder="最低温度" 
                style="width: 100%;" 
                @change="() => formRef?.validateField('max_temperature')" 
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最高温度(°C)" field="max_temperature">
              <a-input-number 
                v-model="formModel.max_temperature" 
                :precision="1" 
                :step="0.5" 
                placeholder="最高温度" 
                style="width: 100%;" 
                @change="() => formRef?.validateField('min_temperature')" 
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="最低湿度(%)" field="min_humidity">
              <a-input-number 
                v-model="formModel.min_humidity" 
                :precision="0" 
                :step="5" 
                :min="0" 
                :max="100" 
                placeholder="最低湿度" 
                style="width: 100%;" 
                @change="() => formRef?.validateField('max_humidity')" 
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最高湿度(%)" field="max_humidity">
              <a-input-number 
                v-model="formModel.max_humidity" 
                :precision="0" 
                :step="5" 
                :min="0" 
                :max="100" 
                placeholder="最高湿度" 
                style="width: 100%;" 
                @change="() => formRef?.validateField('min_humidity')" 
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="formModel.remark" placeholder="请输入备注信息" :auto-size="{ minRows: 3, maxRows: 5 }"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useWarehouseStore } from '@/stores/warehouse';
import { storeToRefs } from 'pinia';
import { Message, Modal } from '@arco-design/web-vue';
import {
  IconSearch, IconRefresh, IconPlus, IconEdit, IconDelete, IconPoweroff, IconCheckCircle
} from '@arco-design/web-vue/es/icon';

const warehouseStore = useWarehouseStore();
// 使用 storeToRefs 保持响应性
const { warehouseList, warehouseLoading, warehousePagination } = storeToRefs(warehouseStore);

// --- 搜索 --- 
const searchForm = reactive({
  keyword: '',
  type: undefined,
  status: undefined,
});

const fetchTableData = (params = {}) => {
  const mergedParams = {
    // 合并搜索条件
    ...(searchForm.keyword && { keyword: searchForm.keyword }),
    ...(searchForm.type && { type: searchForm.type }),
    ...(searchForm.status !== undefined && { status: searchForm.status }),
    // 合并分页器状态
    page: warehousePagination.value.current,
    size: warehousePagination.value.pageSize,
    ...params, // 允许外部调用覆盖参数，例如搜索时强制 page: 1
  };
  warehouseStore.fetchWarehouses(mergedParams);
};

const handleSearch = () => {
  // 搜索时重置页码到第一页
  warehousePagination.value.current = 1;
  fetchTableData();
};

const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.type = undefined;
  searchForm.status = undefined;
  warehousePagination.value.current = 1; // 重置分页
  fetchTableData();
};

// --- 表格与分页 ---
const columns = [
  { title: '仓库名称', dataIndex: 'name', ellipsis: true, tooltip: true ,width: 80 },
  { title: '仓库编码', dataIndex: 'code', width: 80 },
  { title: '仓库类型', dataIndex: 'type', width: 90 },
  { title: '面积(㎡)', dataIndex: 'area', width: 90 },
  { title: '容量', dataIndex: 'capacity', width: 90 },
  { title: '温度(°C)', slotName: 'temperature', width: 80 },
  { title: '湿度(%)', slotName: 'humidity', width: 80 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 50, align: 'center' },
  { title: '备注', dataIndex: 'remark', ellipsis: true, tooltip: true, width: 150 },
  { title: '操作', slotName: 'actions', width: 230, align: 'center', fixed: 'right' },
];

const handlePageChange = (page) => {
  warehousePagination.value.current = page;
  fetchTableData();
};

const handlePageSizeChange = (pageSize) => {
  warehousePagination.value.pageSize = pageSize;
  warehousePagination.value.current = 1; // 切换每页数量时回到第一页
  fetchTableData();
};

// --- 新增/编辑 Modal ---
const modalVisible = ref(false);
const modalTitle = ref('新增仓库');
const isEdit = ref(false);
const formRef = ref(null);
const submitLoading = ref(false);
const formModel = reactive({
  id: null,
  name: '',
  code: '',
  type: undefined,
  status: 1, // 默认启用
  area: 0,
  capacity: 0,
  min_temperature: 0,
  max_temperature: 0,
  min_humidity: 0,
  max_humidity: 0,
  remark: '',
});

// 辅助校验函数
const validateMaxTemp = (value, callback) => {
  if (formModel.min_temperature !== null && formModel.min_temperature !== undefined && value !== null && value !== undefined) {
    if (Number(value) < Number(formModel.min_temperature)) {
      callback('最高温度不能低于最低温度');
      return;
    }
  }
  callback();
};

const validateMinTemp = (value, callback) => {
  if (formModel.max_temperature !== null && formModel.max_temperature !== undefined && value !== null && value !== undefined) {
    if (Number(value) > Number(formModel.max_temperature)) {
      callback('最低温度不能高于最高温度');
      return;
    }
  }
  callback();
};


const validateMaxHumidity = (value, callback) => {
  if (formModel.min_humidity !== null && formModel.min_humidity !== undefined && value !== null && value !== undefined) {
    if (Number(value) < Number(formModel.min_humidity)) {
      callback('最高湿度不能低于最低湿度');
      return;
    }
  }
  if (value !== null && value !== undefined && (Number(value) < 0 || Number(value) > 100)) {
    callback('湿度必须在 0 到 100 之间');
    return;
  }
  callback();
};

const validateMinHumidity = (value, callback) => {
  if (formModel.max_humidity !== null && formModel.max_humidity !== undefined && value !== null && value !== undefined) {
    if (Number(value) > Number(formModel.max_humidity)) {
      callback('最低湿度不能高于最高湿度');
      return;
    }
  }
  if (value !== null && value !== undefined && (Number(value) < 0 || Number(value) > 100)) {
    callback('湿度必须在 0 到 100 之间');
    return;
  }
  callback();
};

// 表单验证规则
const formRules = {
  name: [{required: true, message: '请输入仓库名称'}],
  code: [
    {required: true, message: '请输入仓库编码'},
    {match: /^[A-Za-z0-9-]+$/, message: '编码只能包含字母、数字和连字符'}
  ],
  type: [{required: true, message: '请选择仓库类型'}],
  status: [{required: true, message: '请选择状态'}],
  min_temperature: [{validator: validateMinTemp}],
  max_temperature: [{validator: validateMaxTemp}],
  min_humidity: [{validator: validateMinHumidity}],
  max_humidity: [{validator: validateMaxHumidity}],
};

// 打开新增模态框
const handleAdd = () => {
  modalTitle.value = '新增仓库';
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 打开编辑模态框
const handleEdit = (record) => {
  modalTitle.value = '编辑仓库';
  isEdit.value = true;
  
  // 填充表单
  Object.keys(formModel).forEach(key => {
    if (record[key] !== undefined) {
      formModel[key] = record[key];
    }
  });
  
  modalVisible.value = true;
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  Object.assign(formModel, {
    id: null,
    name: '',
    code: '',
    type: undefined,
    status: 1, // 默认启用
    area: 0,
    capacity: 0,
    min_temperature: null,
    max_temperature: null,
    min_humidity: null,
    max_humidity: null,
    remark: '',
  });
};

// 关闭模态框
const handleCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 模态框确认前校验
const validateForm = async () => {
  const errors = await formRef.value?.validate();
  if (errors) {
    console.log('表单校验失败:', errors);
    return false; // 阻止 Modal 关闭
  }
  return true; // 校验通过
};

// 模态框确认提交
const handleOk = async () => {
  submitLoading.value = true;
  try {
    const dataToSubmit = { ...formModel };
    
    if (isEdit.value) {
      // 编辑时不需要提交 code
      delete dataToSubmit.code;
      await warehouseStore.updateWarehouse(formModel.id, dataToSubmit);
    } else {
      await warehouseStore.createWarehouse(dataToSubmit);
    }
    
    modalVisible.value = false;
    // 列表刷新逻辑已在 store action 中处理
    return true; // 确认可以关闭 Modal
  } catch (error) {
    // store action 内部会提示错误信息
    return false; // 阻止 Modal 关闭
  } finally {
    submitLoading.value = false;
  }
};

// --- 删除 --- 
const handleDelete = async (id) => {
  await warehouseStore.deleteWarehouse(id);
  // 刷新和提示在 store action 中
};

// --- 状态切换 ---
const toggleStatus = async (record) => {
  const newStatus = record.status === 1 ? 0 : 1;
  const actionText = newStatus === 1 ? '启用' : '禁用';
  
  Modal.confirm({
    title: `确认${actionText}`,
    content: `确定要${actionText}仓库 "${record.name}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const success = await warehouseStore.updateWarehouse(record.id, { status: newStatus });
      if(success) {
        Message.success(`${actionText}成功`);
      }
      // 失败提示和刷新在 store action 中
    }
  });
};

// --- 生命周期 ---
onMounted(() => {
  // fetchTableData(); // <--- 注释掉旧的调用
  warehouseStore.fetchWarehouses(); // <--- 直接调用 store action 获取初始数据
});
</script>

<style scoped lang="less">
@import '@/styles/variables.less';

.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  margin-top: 16px;
  margin-bottom: 20px;
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
}

.search-form {
  margin-bottom: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

:deep(.arco-modal-footer .arco-btn),
:deep(.modal-footer .arco-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style> 